//
//  YouhuiDetailViewController.m
//  PlayerWorld
//
//  Created by 汪的一声就哭了！ on 16/8/15.
//  Copyright © 2016年 刘成. All rights reserved.
//

#import "YouhuiDetailViewController.h"
#import "UIImageView+WebCache.h"
#import "AFNetworking.h"
#import "YouhuiHeader.h"
#import "TimeLabelTableViewCell.h"
#import "HuodongContentTableViewCell.h"
#import "Content1TableViewCell.h"
#import "Content2TableViewCell.h"
@interface YouhuiDetailViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImageView *imageView;
@end

@implementation YouhuiDetailViewController
{
    NSArray *_sectionArr;
    //活动时间
    NSString *_A_L_Time;
    //活动规则（内容）
    NSArray *_rules;
    //活动内容
    NSString *_A_L_Contents;
    //图片
    NSString *_A_L_Html;
    //活动条款
    NSString *_A_L_Provision;
    //昨日工资
    NSString *_rgz;
    //昨日消费总量
    NSString *_zxf;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self obtainData];
    self.title = self.name;
    _sectionArr = @[@"活动时间",@"活动内容",@"活动条款"];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-64)];
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.width/2)];
    self.tableView.tableHeaderView = self.imageView;
    
    [self.tableView registerClass:[YouhuiHeader class] forHeaderFooterViewReuseIdentifier:@"header"];
    [self.tableView registerClass:[TimeLabelTableViewCell class] forCellReuseIdentifier:@"cell1"];
    [self.tableView registerClass:[Content1TableViewCell class] forCellReuseIdentifier:@"cell3"];
    [self.tableView registerNib:[UINib nibWithNibName:@"HuodongContentTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell2"];
    [self.tableView registerClass:[Content2TableViewCell class] forCellReuseIdentifier:@"cell4"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _sectionArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 || (section == 1&& _rules.count == 0)) {
        return 1;
    }
    else if (section == 1){
        if (![_rules.firstObject isKindOfClass:[NSArray class]]) {
            return 1;
        }
        return _rules.count;
    }
    else if (section == 2){
        return 1;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 || (_rules.count == 0 && indexPath.section == 1) || indexPath.section == 2) {
        TimeLabelTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell1"];
        if (indexPath.section == 0) {
            cell.timeLabel.text = _A_L_Time;
        }
        else if (indexPath.section == 1){
            cell.timeLabel.text = _A_L_Contents;
        }
        else if (indexPath.section == 2){
            cell.timeLabel.text = _A_L_Provision;
        }
        return cell;
    }
    else if (indexPath.section == 1){
        if (![_rules.firstObject isKindOfClass:[NSArray class]]) {
            Content2TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell4"];
            cell.mainLabel.text = [NSString stringWithFormat:@"团队消费量%@起，活跃会员人数无要求，日工资（无间隙）%@。\n日结奖励为%@起，无间隙，上限%@\n昨日总消费量：%@元，昨日工资：%@元",_rules.firstObject,_rules[2],_rules.firstObject,_rules.lastObject,_zxf,_rgz];
            [cell.mainBtn addTarget:self action:@selector(mainBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            return cell;
        }
        else if ([_rules.firstObject count] == 3) {
            Content1TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell3"];
            cell.firstLabel.text = [NSString stringWithFormat:@"会员当日亏损：%@元",[_rules[indexPath.row] firstObject]];
            cell.secLabel.text = [NSString stringWithFormat:@"上级佣金：%@元，上上级佣金：%@元",[_rules[indexPath.row] objectAtIndex:1],[_rules[indexPath.row] lastObject]];
            return cell;
        }
        HuodongContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell2"];
        NSArray *array = _rules[indexPath.row];
        cell.firstLabel.text = [NSString stringWithFormat:@"会员当日消费：%@元",array.firstObject];
        cell.secLabel.text = [NSString stringWithFormat:@"会员当日领取：%@元",array.lastObject];
        cell.btn.tag = 1000+indexPath.row;
        [cell.btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *string;
    if (indexPath.section == 0) {
        string = _A_L_Time;
    }
    else if (indexPath.section == 1 && _rules.count == 0){
        string = _A_L_Contents;
    }
    else if (indexPath.section == 2){
        string = _A_L_Provision;
    }
    else if (indexPath.section == 1){
        if (![_rules.firstObject isKindOfClass:[NSArray class]]) {
            NSString *astring = [NSString stringWithFormat:@"团队消费量%@起，活跃会员人数无要求，日工资（无间隙）%@。\n日结奖励为%@起，无间隙，上限%@\n昨日总消费量：%@元，昨日工资：%@元",_rules.firstObject,_rules[2],_rules.firstObject,_rules.lastObject,_zxf,_rgz];
            CGRect arect = [astring boundingRectWithSize:CGSizeMake(self.view.bounds.size.width-20, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
            return arect.size.height+40;
        }
        else{
            return 65;
        }
    }
    CGRect rect = [string boundingRectWithSize:CGSizeMake(self.view.bounds.size.width-20, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
    return rect.size.height+10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    YouhuiHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"header"];
    header.mainImageView.image = [UIImage imageNamed:[_sectionArr objectAtIndex:section]];
    header.label.text = _sectionArr[section];
    return header;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)btnAction:(UIButton *)btn
{
    NSInteger index = btn.tag-1000;
    [self obtainData1WithIndex:[NSString stringWithFormat:@"%ld",index]];
}
-(void)obtainData
{
    // 启动系统风火轮
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    //服务器给的域名
    NSString *domainStr = @"http://666.lefun6.com/";
    
    //创建一个可变字典
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    //往字典里面添加需要提交的参数
    [parametersDic setObject:@"Events" forKey:@"Model"];
    [parametersDic setObject:@"get_event_details" forKey:@"Action"];
    [parametersDic setObject:self.a_id forKey:@"Id"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //以post的形式提交，POST的参数就是上面的域名，parameters的参数是一个字典类型，将上面的字典作为它的参数
    [manager POST:domainStr parameters:parametersDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 解析成功隐藏系统风火轮
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        _rgz = dic[@"otherinfo"][@"{rgz}"];
        _zxf = dic[@"otherinfo"][@"{zxf}"];
        _A_L_Time = dic[@"info"][@"A_L_Time"];
        _rules = dic[@"rules"];
        _A_L_Contents = dic[@"info"][@"A_L_Contents"];
        _A_L_Provision = dic[@"info"][@"A_L_Provision"];
        _A_L_Html = [dic[@"info"][@"A_L_Html"] stringByReplacingOccurrencesOfString:@"<img src=\"{hx_images}" withString:@"http://static.public.ms/lf/Template/Skin_1/images/activity/"];
        _A_L_Html = [_A_L_Html stringByReplacingOccurrencesOfString:@"\">" withString:@""];
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:_A_L_Html]];
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
    }];
    
}
-(void)obtainData1WithIndex:(NSString *)index
{
    // 启动系统风火轮
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    //服务器给的域名
    NSString *domainStr = @"http://666.lefun6.com/";
    
    //创建一个可变字典
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    //往字典里面添加需要提交的参数
    [parametersDic setObject:@"Events" forKey:@"Model"];
    [parametersDic setObject:@"ParticipateActivity" forKey:@"Action"];
    [parametersDic setObject:self.a_id forKey:@"Id"];
    [parametersDic setObject:index forKey:@"index"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //以post的形式提交，POST的参数就是上面的域名，parameters的参数是一个字典类型，将上面的字典作为它的参数
    [manager POST:domainStr parameters:parametersDic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 解析成功隐藏系统风火轮
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        UIAlertController *alerView = [UIAlertController alertControllerWithTitle:@"提示信息" message:[dic objectForKey:@"msg"] preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alerView addAction:action];
        [self presentViewController:alerView animated:YES completion:nil];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 解析失败隐藏系统风火轮(可以打印error.userInfo查看错误信息)
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
    }];
    
}
- (void)mainBtnAction:(UIButton *)btn
{
    [self obtainData1WithIndex:@""];
}
-(NSString *)filterHTML:(NSString *)html
{
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = nil;
    while([scanner isAtEnd]==NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">" intoString:&text];
        //替换字符
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@"  "];
    }
    //    NSString * regEx = @"<([^>]*)>";
    //    html = [html stringByReplacingOccurrencesOfString:regEx withString:@""];
    return html;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
